package cn.conac.rc.ofs.service;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.ofs.contsant.Contsants;
import cn.conac.rc.ofs.entity.OrgLibInfoEntity;
import cn.conac.rc.ofs.repository.OrgLibInfoRepository;
import cn.conac.rc.ofs.vo.OrgLibInfoVo;

/**
 * OrgLibInfoService类
 *
 * @author serviceCreator
 * @date 2017-07-10
 * @version 1.0
 */
@Service
public class OrgLibInfoService extends GenericService<OrgLibInfoEntity, Integer> {

	@Autowired
	private OrgLibInfoRepository repository;

	/**
	 * 动态查询，分页，排序查询
	 * @param vo
	 * @return Page
	 * @throws Exception
	 */
	public Page<OrgLibInfoEntity> list(OrgLibInfoVo vo) throws Exception {
		try {
			Sort sort = new Sort(Direction.ASC, "orgName");
			Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
			Criteria<OrgLibInfoEntity> dc = this.createCriteria(vo);
			return repository.findAll(dc, pageable);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 * @param param
	 * @return Criteria
	 */
	private Criteria<OrgLibInfoEntity> createCriteria(OrgLibInfoVo param) {
		Criteria<OrgLibInfoEntity> dc = new Criteria<OrgLibInfoEntity>();
		
		if (StringUtils.isNotBlank(param.getAreaId())) {
			dc.add(Restrictions.eq("areaId", param.getAreaId(), true));
		}
		if (StringUtils.isNotBlank(param.getAreaCode())) {
			dc.add(Restrictions.eq("areaCode", param.getAreaCode(), true));
		}
		if (StringUtils.isNotBlank(param.getType())) {
			dc.add(Restrictions.eq("type", param.getType(), true));
		}
		if (param.getParentId()!=null) {
			dc.add(Restrictions.eq("parentId", param.getParentId(), true));
		}
		if (StringUtils.isNotBlank(param.getIsComp())) {
			dc.add(Restrictions.eq("isComp", param.getIsComp(), true));
		}
		if (StringUtils.isNotBlank(param.getOrgName())) {
			dc.add(Restrictions.like("orgName", param.getOrgName(), true));
		}
		if (StringUtils.isNotBlank(param.getOwnSys())) {
			dc.add(Restrictions.eq("ownSys", param.getOwnSys(), true));
		}
		if (StringUtils.isNotBlank(param.getStatus())) {
			dc.add(Restrictions.eq("status", param.getStatus(), true));
		} else {
			dc.add(Restrictions.or(Restrictions.eq("status", Contsants.OFS_ORGANIZATION_FLAG_NORMAL, true),
					Restrictions.eq("status", Contsants.OFS_ORGANIZATION_FLAG_CANCEL, true)));
		}
		return dc;
	}

}
